// Compile :: g++ server.cpp -o server -lnsl -lsocket -lresolv


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#include <iostream>
#include <stdio.h>

#define SOCKET_ERROR -1
#define SD_SEND 1
#define INVALID_SOCKET -1


#ifndef INADDR_NONE
#define INADDR_NONE ((unsigned long) -1)
#endif

using namespace std;

/*  Resolve IP Address into a usable address  */
u_long ResolveAddress(const char *serverIp)
{
	//Assume X.X.X.X format of IP address was passed
	u_long address = inet_addr(serverIp);
	
	//if IP address is not valid IP address then try to do DNS Resolution
	if(address == INADDR_NONE)
	{
		cout<<"address was not valid IP \n";
		hostent* hostEntry = gethostbyname(serverIp);
		
		if(hostEntry == 0)
		{ // Get the latest Error Message and display it
			return INADDR_NONE;
		}
		
		address = *((u_long*)hostEntry->h_addr);
	}
	
	return address;
}


int main()
{
	string serverIp = "127.0.0.1";
	int port = 15687;
	//int port = 15686
	int mySocket;
	
	sockaddr_in sinRemote;
	
	u_long address = ResolveAddress(serverIp.c_str());
	cout<<address<<endl;
	
	// Create a stream socket
	mySocket = socket(AF_INET,SOCK_STREAM,0);
	
	if(mySocket != INVALID_SOCKET)
	{
		sinRemote.sin_family = AF_INET;
		sinRemote.sin_addr.s_addr = address;
		sinRemote.sin_port = htons(port);
		
		int c = bind(mySocket,(sockaddr*)&sinRemote, sizeof(sockaddr_in));
		
		if( c == SOCKET_ERROR)
		{
			cout << "Error connecing to remote process:"<<strerror(errno)<<endl;
		}
		
	}
	
	socklen_t *addressLength = new socklen_t;
	*addressLength = 100;
	
	int listenReturn = listen(mySocket , 5);
	int acceptReturn = accept(mySocket,(sockaddr*)&sinRemote, addressLength);
	
	cout<<"Address Length : "<<*addressLength<<endl;
	
	char acReadBuffer[100];
	
	for(int i=0; i<100; i++)
	{
		acReadBuffer[i]='\0';
	}
	
	int nNewBytes = recv(acceptReturn, acReadBuffer , 100 ,0);
	
	cout<<"Bytes Received :"<<nNewBytes<<endl;
	
	for(int i=0; i<20; i++)
	{
		printf("%d",acReadBuffer[i]);
	}
	
	cout<<"message:"<<acReadBuffer[0]<<acReadBuffer[1]<<endl;
	
	return 0;
}
